package com.yinhe.music.yhmusic.localmusic.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.common.utils.ScreenUtils;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.ViewPagerFragment;
import com.yinhe.music.yhmusic.cache.CacheManager;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.constants.KeyConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.DownloadMusicEntity;
import com.yinhe.music.yhmusic.dialog.more.MoreDialog;
import com.yinhe.music.yhmusic.downmusic.DownloadTask;
import com.yinhe.music.yhmusic.localmusic.adapter.LocalMusicAdapter;
import com.yinhe.music.yhmusic.log.BlankUtil;
import com.yinhe.music.yhmusic.manager.ManageActivity;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.utils.DataHolder;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by hasee on 2017/8/14.
 */

public class LocalMusicFragment extends ViewPagerFragment implements BaseQuickAdapter.OnItemClickListener, View.OnClickListener, BaseQuickAdapter.OnItemChildClickListener {

    public static final String TAG = "LocalMusicFragment";
    @BindView(R.id.recommend_music_recyclerview)

    RecyclerView mRecyclerview;
    Unbinder                                                                                                                                                                                                                                                                        unbinder;
    private TextView mPlayNum;
    private List<Music> musicList = new ArrayList<>();
    private boolean hasHead;
    private LocalMusicAdapter mAdapter;

    public static LocalMusicFragment newInstance(boolean hasHead) {
        Bundle args = new Bundle();
        args.putBoolean("hasHead", hasHead);
        LocalMusicFragment fragment = new LocalMusicFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recycler_layout, container, false);
        unbinder = ButterKnife.bind(this, view);
        RxBus.get().register(this);
        if (getArguments() != null) {
            hasHead = getArguments().getBoolean("hasHead");
        }
        if (hasHead) {
            musicList = CacheManager.getInstance().getIntentList();
        } else {
            musicList = CacheManager.getInstance().getScanMusic();
        }
        initDownList();
        initView(inflater);
        return view;
    }


    @Override
    public void onDestroyView() {
        RxBus.get().unregister(this);
        super.onDestroyView();
        unbinder.unbind();
    }

    private void initDownList() {
        List<Music> original = new ArrayList<>();
        List<Music> replaceList = new ArrayList<>();
        if (musicList != null && !musicList.isEmpty()) {
            for (Music music : musicList) {
                DownloadMusicEntity downloadMusicEntity = DataBaseAccessor.getInstance().getDownMusicByPath(music.filePath);
                if (downloadMusicEntity != null) {
                    original.add(music);
                    Music replaceMusic = new Music(downloadMusicEntity);
                    replaceMusic.setLocalMusic(true);
                    replaceMusic.setFileType(Music.Type.LOCAL);
                    replaceList.add(replaceMusic);
                }
            }
            musicList.removeAll(original);
            musicList.addAll(replaceList);
        }
    }

    private void initView(LayoutInflater inflater) {
        mAdapter = new LocalMusicAdapter(musicList);
        mAdapter.setEmptyView(inflater.inflate(R.layout.include_empty_layout, (ViewGroup) mRecyclerview.getParent(), false));
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mRecyclerview.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        mRecyclerview.setHasFixedSize(true);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, ScreenUtils.dp2px(20), false);
        mRecyclerview.addItemDecoration(itemDecoration);
        mRecyclerview.setAdapter(mAdapter);
        if (hasHead) {
            mAdapter.addHeaderView(getHeadView(inflater));
        }
    }

    private View getHeadView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.header_musiclist, (ViewGroup) mRecyclerview.getParent(), false);
        LinearLayout mPlayLayout = view.findViewById(R.id.play_layout);
        mPlayNum = view.findViewById(R.id.play_num);
        LinearLayout mManagerLayout = view.findViewById(R.id.manager);
        TextView mManagerText = view.findViewById(R.id.manager_text);
        mManagerText.setText("多选");
        mPlayLayout.setOnClickListener(this);
        mManagerLayout.setOnClickListener(this);
        return view;
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (mService != null) {
            List<Music> musicList = adapter.getData();
            mService.playPosition(musicList, position);
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        Music music = (Music) adapter.getData().get(position);
        if (music.fileType == Music.Type.LOCAL) {
            LocalMusicDialog dialog = LocalMusicDialog.newInstance(music, IConstants.LOCAL_MUSIC, null);
            dialog.show(getFragmentManager(), KeyConstants.KEY_LOCAL_MUSIC_DIALOG);
        } else {
            MoreDialog moreDialog = MoreDialog.newInstance(music, 0, IConstants.PLAYING_MUSIC_MANAGER);
            moreDialog.show(getFragmentManager(), "MoreDialog");
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.manager:
                Intent intent = new Intent(getActivity(), ManageActivity.class);
                intent.putExtra("type", Music.Type.LOCAL);
                DataHolder.getInstance().setData(musicList);
                startActivity(intent);
                break;
            case R.id.play_layout:
                if (mService != null) {
                    mService.playAll(musicList);
                }
                break;
            default:
                break;
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Local.DELETE_LOCAL_MUSIC)
    )
    public void onRxbusLocalMusic(RxbusListObject rxbusListObject) {
        if (rxbusListObject == null) {
            return;
        }
        List<Music> deleteList = (List<Music>) rxbusListObject.rxList;
        if (deleteList != null) {
            if (!BlankUtil.isBlank(musicList)) {
                musicList.removeAll(deleteList);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Download.DOWNLOAD_COMPLETE)
    )
    public void onRxbusDownloadComplete(DownloadTask downloadTask) {
        musicList = CacheManager.getInstance().getScanMusic();
        mAdapter.notifyDataSetChanged();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Music.DELETE_DOWN_MUSIC)})
    public void onRxbusDeleteDownMusic(RxbusListObject rxbusListObject) {
        if (rxbusListObject != null) {
            for (Music i : musicList) {
                for (Object j : rxbusListObject.rxList){
                    Integer songId = (Integer) j;
                    if (i.getSongId() == songId) {
                        musicList.remove(i);
                    }
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }
}
